package top.ahzy.seobench.util;


import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsRequest;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsResponse;
import com.aliyuncs.alidns.model.v20150109.UpdateDomainRecordRequest;
import com.aliyuncs.profile.DefaultProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.ahzy.seobench.config.AliyunConfig;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

@Component
public class AlyDdnsUtil {

    private static final Logger logger = LoggerFactory.getLogger(AlyDdnsUtil.class);
    private static final String ACCESS_KEY_ID = "LTAI5tJeDTZSNHBYDFUjnyMm";
    private static final String ACCESS_KEY_SECRET = "hYLMuYrcy6LfRrfHDnq5aZMokoIAFw";
    private static final String AREA = "cn-hangzhou";

    @Autowired
    AliyunConfig aliyunConfig;

    /**
     * 更新ddns
     * @throws Exception
     */
    public void updateAAAARecord() throws Exception {
        URL url = new URL("http://6.ipw.cn");
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        String ipv6 = reader.readLine().trim();

        DefaultProfile profile = DefaultProfile.getProfile(aliyunConfig.getDdns().getArea(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        // 获取当前记录
        DescribeDomainRecordsRequest describeRequest = new DescribeDomainRecordsRequest();
        describeRequest.setDomainName(aliyunConfig.getDdns().getDomain().get(0).getDomainName());
        describeRequest.setRRKeyWord(aliyunConfig.getDdns().getDomain().get(0).getSubDomain());
        DescribeDomainRecordsResponse describeResponse = client.getAcsResponse(describeRequest);
        // 更新记录
        if (!describeResponse.getDomainRecords().isEmpty() && !ipv6.equals(describeResponse.getDomainRecords().get(0).getValue())) {
            UpdateDomainRecordRequest updateRequest = new UpdateDomainRecordRequest();
            updateRequest.setRecordId(describeResponse.getDomainRecords().get(0).getRecordId());
            updateRequest.setRR(aliyunConfig.getDdns().getDomain().get(0).getSubDomain());
            updateRequest.setType(aliyunConfig.getDdns().getDomain().get(0).getRecordType());
            updateRequest.setValue(ipv6);
            client.getAcsResponse(updateRequest);
            logger.info("ddns修改前：{};修改后：{}",describeResponse.getDomainRecords().get(0).getValue(),ipv6);
        }
    }



}
